package com.ruoyi.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Anonymous;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/tshock")
@CrossOrigin("*")
@Anonymous
@Tag(name = "TShock服务器命令接口", description = "直接返回TShock服务器响应结果")
public class thoskcmd {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private RestTemplate restTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/cmd")
    @Operation(summary = "执行服务器命令", description = "直接返回TShock服务器的响应结果（status+response结构）")
    public Object executeCommand(
            @Parameter(description = "服务器UUID", required = true) @RequestParam String uuid,
            @Parameter(description = "要执行的命令，默认/who") @RequestParam(required = false, defaultValue = "/who") String cmd) {
        
        // 1. 查询服务器信息
        String sql = "SELECT server_ip, rest_port, token FROM tshock_info WHERE uuid = ?";
        List<Map<String, Object>> serverInfoList = jdbcTemplate.queryForList(sql, uuid);
        
        // 异常情况1：未找到服务器
        if (serverInfoList.isEmpty()) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("status", "404"); // 用404表示未找到
            errorMap.put("response", new String[]{"未找到指定UUID的服务器信息"});
            return errorMap;
        }
        
        // 2. 构建请求参数
        Map<String, Object> serverInfo = serverInfoList.get(0);
        String serverIp = (String) serverInfo.get("server_ip");
        int restPort = (Integer) serverInfo.get("rest_port");
        String token = (String) serverInfo.get("token");
        String url = String.format("http://%s:%d/v3/server/rawcmd?cmd=%s&token=%s",
                serverIp, restPort, cmd, token);
        
        try {
            // 3. 调用TShock服务器并直接返回其响应（已解析为JSON对象）
            String tshockResponseStr = restTemplate.getForObject(url, String.class);
            return objectMapper.readValue(tshockResponseStr, Map.class); // 直接返回解析后的结果
            
        } catch (JsonProcessingException e) {
            // 异常情况2：响应解析失败
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("status", "500"); // 用500表示服务器错误
            errorMap.put("response", new String[]{"解析服务器响应失败: " + e.getMessage()});
            return errorMap;
        } catch (Exception e) {
            // 异常情况3：请求失败（如连接超时、token错误等）
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("status", "500");
            errorMap.put("response", new String[]{"执行命令失败: " + e.getMessage()});
            return errorMap;
        }
    }

    
}
